﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applications.Command.UploadImage;
using Tb.App.Domain;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.UploadImage
{
    /// <summary>
    /// 删除图片处理命令
    /// </summary>
    public class DelBatchImageCommandHandler : IRequestHandler<DelBatchImageCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Images> imagesRep;
        private readonly IWebHostEnvironment web;

        public DelBatchImageCommandHandler(IBaseRepository<Images>imagesRep,
            IWebHostEnvironment web)
        {
            this.imagesRep = imagesRep;
            this.web = web;
        }
        public async Task<ApiResult<int>> Handle(DelBatchImageCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            // 查询图片信息
            var image = await imagesRep.GetById(request.Id);
            if (image == null)
                return new ApiResult<int>
                {
                    Code = ApiEnum.删除失败,
                    Message = "图片不存在或已被删除",
                    Data = -1
                };
            // 删除图片
            var fullPath = Path.Combine(web.WebRootPath, image.ImagePath.TrimStart('/'));
            if (File.Exists(fullPath))
            {
                try
                {
                    File.Delete(fullPath);
                }
                catch (Exception ex)
                {
                    // 记录日志：文件删除失败，但仍继续删除数据库记录
                    // _logger.LogError(ex, $"删除图片文件失败: {fullPath}");
                }
            }
            image.IsDel= true;
            await imagesRep.UpdateAsync(image);
            return new ApiResult<int>
            {
                Code = ApiEnum.删除成功,
                Message = "删除成功",
                Data = 1
            };
        }
    }
}
